<template>
  <div v-show="!is_loading" class="hero" :class="is_dark ? 'bg-dark' : 'bg-gray'">
    <Navbar />
    <Question />
  </div>
  <div v-show="is_loading" class="loading loading-lg"></div>
</template>

<script>
import { mapState } from 'vuex'
import Question from '../components/Question.vue'
import Navbar from '../components/Navbar.vue'

export default {
  name: 'Recite',
  components: {
    Question,
    Navbar
  },
  data() {
    return {
      is_loading: true,
    }
  },
  computed: mapState(['is_dark', 'user_answer', 'questions', 'index', 'curr_status']),
  created() {
    // 创建之前进行初始化
    console.log('Recite Page: created')
    this.$store.commit('set_curr_status', this.$route.query.mode)
    // 清空用户答案
    this.user_answer.splice(0, this.user_answer.length)
    // 设置当前题目索引
    this.$store.commit('set_index', 0)
    // 请求数据
    const url = this.$route.query.mode === 'exam' ? '/api/make_exam' : '/api/get_line'
    this.$axios.post(url, this.$route.query).then(res => {
      // 题目数据导入
      this.$store.commit('set_questions', res.data.data)
      // 初始化题目状态
      this.$store.commit(
        'set_ques_status',
        new Array(this.questions.length).fill(null)
      )
      // 初始化题目答案信息
      for (let i = 0; i < this.questions.length; i++) {
        if (this.questions[i].questionType === 'fillblank') {
          this.user_answer.push(Array.from({ length: this.questions[i].options.length }, () => ''))
        } else if (this.questions[i].questionType === 'checkbox') {
          this.user_answer.push([])
        } else {
          this.user_answer.push('')
        }
      }
      if (this.curr_status === 'recite') {
        // 如果是背题模式，则设置题目答案
        for (let i = 0; i < this.questions.length; i++) {
          if (this.questions[i].questionType === 'radio') {
            this.user_answer[i] = this.questions[i].answer
          } else if (this.questions[i].questionType === 'checkbox') {
            this.user_answer[i] = this.questions[i].answer.split(',')
          } else if (this.questions[i].questionType === 'fillblank') {
            // this.user_answer[i] = new Array(this.questions[i].options.length)
            for (let j = 0; j < this.questions[i].options.length; j++) {
              this.user_answer[i][j] = this.questions[i].options[j].content
            }
          } else {
            this.user_answer[i] = this.questions[i].answer
          }
        }
      }
      // 初始化结束
      this.is_loading = false
    })
  },
  methods: {
    next_st() {
      this.$store.commit('set_index', (this.index + 1) % this.questions.length)
    }
  }
}
</script>

<style scoped>
.loading {
  position: relative;
  top: 30vh;
}
</style>